package com.example.shop.controller;

import com.example.shop.bean.UserBean;
import com.example.shop.bean.VxResp;
import com.example.shop.mapper.UserMapper;
import com.example.shop.util.FileUtil;
import com.example.shop.util.NotNullUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class UserController {

    @Autowired // new
    UserMapper userMapper;


    @ResponseBody  //返回值转为字符串形式!!!!!
    @RequestMapping("/login/vx")
    public VxResp login(UserBean bean){
        VxResp vx = new VxResp();
        if(NotNullUtil.isBlank(bean)){
            vx.fail("请完善信息");
            return vx;
        }
        bean.status = "买家";
        if(userMapper.haveUser(bean.username)!=null){
            //账号已经存在的情况
            UserBean user = userMapper.getUser(bean);

            if(user == null){
                vx.fail("您的密码错误");
            }else{
                //返回个人id
                vx.uid= String.valueOf(user.id);
            }
        }else{
            //账号不存在
            bean.user=bean.username; //昵称和用户名一样
            userMapper.insert(bean);//新人注册到用户表中
            vx.uid= String.valueOf(bean.id);
        }

        return vx;  //对象转成String返回给java
    }


    //直接使用地址框传参
    @RequestMapping("/login")
    public String login(UserBean bean, HttpServletRequest req) throws UnsupportedEncodingException {
        bean.status="卖家";
        UserBean user = userMapper.getUser(bean);
        if(user == null){
            System.out.println("用户名或者密码错误");
            return "redirect:/index.html?msg=" + URLEncoder.encode("用户名或密码错误", "utf-8");
        }else{
            System.out.println("登录成功");

            return "redirect:/main?uid=" + user.id;
        }
    }


    @RequestMapping("/main")
    public String main(int uid, HttpServletRequest req){
        // 按照id查询记录
        req.setAttribute("user", userMapper.selectById(uid));

        return "/main";
    }

    @ResponseBody
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws Exception{
        String fileName =file.getOriginalFilename();
        System.out.println(fileName);
        FileUtil.createFile("D:/create/shop/upload");
        file.transferTo(new File("D:/create/shop/upload/"+fileName));
        return "/shop/upload/" + fileName;
    }

}
